package com.asen.app.base

import android.text.TextUtils
import android.view.KeyEvent
import android.view.View
import com.alibaba.android.arouter.launcher.ARouter
import com.asen.libbase.databinding.ActivityBaseX5WebViewBinding
import com.asen.libcommon.base.iface.BaseJSCall
import com.asen.libcommon.base.viewbind.BaseViewBindActivity
import com.asen.libcommon.base.viewbind.viewBind
import com.asen.libcommon.widget.BaseX5WebView
import com.orhanobut.logger.Logger
import com.tencent.smtt.sdk.ValueCallback

/**
 * @date   : 2021/12/23
 * @author : asenLiang
 * @e-mail : 375427684@qq.com
 * @desc   :
 */
abstract class BaseX5WebViewActivity<T : BaseJSCall> : BaseViewBindActivity<ActivityBaseX5WebViewBinding>() {

    abstract fun onToolbarTitle(): String // 标题名字
    abstract fun isShowToolbar(): Boolean // 是否显示标题
    abstract fun webUrl(): String         // 地址
    abstract fun clearCache(): Boolean    // 是否刪除所有緩存

    override val mBinding: ActivityBaseX5WebViewBinding by viewBind()

    override suspend fun initView() {
        super.initView()
        ARouter.getInstance().inject(this)
        mBinding.apply {
            if (isShowToolbar()) {
                mBaseTitle.setTitle(onToolbarTitle())
            } else {
                mBaseTitle.visibility = View.GONE
            }
            if (!TextUtils.isEmpty(webUrl())) mBaseX5WebView.loadUrl(webUrl())
            mBaseTitle?.setLeftClick { mBaseX5WebView.goBack(this@BaseX5WebViewActivity) }
        }

    }


    protected fun getWebView(): BaseX5WebView =mBinding.mBaseX5WebView

    /**
     * 返回键监听
     * @param keyCode Int
     * @param event KeyEvent
     * @return Boolean
     */
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return goBack()
        }
        return false
    }

    /**
     * webView 返回上一层 或退出当前界面
     */
    private fun goBack(): Boolean {
        return mBinding.mBaseX5WebView.goBack(this)
    }

    override fun onDestroy() {
        try {
            mBinding.mBaseX5WebView.destroy(clearCache())
        } catch (e: Exception) {
            Logger.d(e.message)
        }
        super.onDestroy()
    }

    /**
     * android触发js方法或往js添加新元素
     */
    protected fun addJsAction(actionName: String, callback: ValueCallback<String>?) {
        mBinding.mBaseX5WebView.addJsAction(actionName, callback)
    }

    protected fun loadUrl(url: String? = "") {
        mBinding.mBaseX5WebView.loadUrl(url)
    }

}